/// @Author: 桫椤
/// @Date: 2021-09-26
/// @Description: 弹框组件
/// @LastEditors: 初然 2022-01-24

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jetour_line/my_colors.dart';
import 'package:jetour_line/utils/extension_int.dart';

class SPDialog extends Dialog {
  /// 标题
  final String? title;

  /// 内容
  final String? content;

  /// 内容widget
  final Widget? contentWidget;

  /// 内容对齐方式
  final TextAlign? contentAlign;

  /// 内容内边距
  final EdgeInsetsGeometry? contentPadding;

  /// 按钮
  final List<String>? items;

  /// 点击事件 回调序列
  final ValueChanged<int>? onTap;

  /// 是否显示输入框
  final bool? showTextField;

  /// 输入框点击确认 回调输入内容
  final ValueChanged<String>? textFieldOnConfirm;

  /// 输入框占位符
  final String? textFieldHintText;

  /// 输入框最大输入
  final int? textFieldMaxLength;

  /// 输入框是否可编辑
  final bool? textFieldEnabled;

  /// 自定义弹出框
  const SPDialog({
    Key? key,
    this.title,
    this.items,
    this.content,
    this.contentAlign = TextAlign.center,
    this.contentPadding,
    this.onTap,
  })  : showTextField = null,
        textFieldEnabled = null,
        textFieldOnConfirm = null,
        textFieldHintText = null,
        textFieldMaxLength = null,
        contentWidget = null,
        super(key: key);

  /// 内容自定义widget
  SPDialog.contentCustom(
      {Key? key,
      this.title = '提示',
      this.contentWidget,
      this.contentPadding,
      String cancel = '取消',
      VoidCallback? onCancel,
      String confirm = '确认',
      VoidCallback? onConfirm})
      : items = [cancel, confirm],
        onTap = ((index) {
          if (index == 0) {
            if (onCancel != null) {
              onCancel();
            }
          } else {
            if (onConfirm != null) {
              onConfirm();
            }
          }
        }),
        contentAlign = null,
        showTextField = null,
        textFieldEnabled = null,
        textFieldOnConfirm = null,
        textFieldHintText = null,
        textFieldMaxLength = null,
        content = '',
        super(key: key);

  /// 只有单个按钮的提示弹出框
  SPDialog.singleItem({
    Key? key,
    this.title = '提示',
    this.content,
    this.contentPadding,
    String cancel = '取消',
    VoidCallback? onCancel,
  })  : items = [cancel],
        onTap = ((index) {
          if (onCancel != null) {
            onCancel();
          }
        }),
        contentAlign = TextAlign.center,
        showTextField = null,
        textFieldEnabled = null,
        textFieldOnConfirm = null,
        textFieldHintText = null,
        textFieldMaxLength = null,
        contentWidget = null,
        super(key: key);

  /// 只有两个按钮的提示弹出框
  SPDialog.doubleItem(
      {Key? key,
      this.title = '提示',
      this.content,
      this.contentPadding,
      String cancel = '取消',
      VoidCallback? onCancel,
      String confirm = '确认',
      VoidCallback? onConfirm})
      : items = [cancel, confirm],
        onTap = ((index) {
          if (index == 0) {
            if (onCancel != null) {
              onCancel();
            }
          } else {
            if (onConfirm != null) {
              onConfirm();
            }
          }
        }),
        contentAlign = TextAlign.center,
        showTextField = null,
        textFieldEnabled = null,
        textFieldOnConfirm = null,
        textFieldHintText = null,
        textFieldMaxLength = null,
        contentWidget = null,
        super(key: key);

  /// 文本输入弹出框
  const SPDialog.textField({
    Key? key,
    this.title,
    this.items,
    this.contentPadding,
    ValueChanged<String>? onConfirm,
    String hintText = '请输入内容',
    int maxCount = 20,
    bool enabled = true,
  })  : content = '',
        contentAlign = TextAlign.center,
        onTap = null,
        showTextField = true,
        textFieldOnConfirm = onConfirm,
        textFieldHintText = hintText,
        textFieldMaxLength = maxCount,
        textFieldEnabled = enabled,
        contentWidget = null,
        super(key: key);

  /// 展示弹框
  void showAlert({required BuildContext context}) {
    showDialog(
      context: context ,
      builder: (context) {
        return _ShowAlertDialog(this);
      },
    );
  }

  void dismiss({required BuildContext context}) {
    Navigator.pop(context);
  }
}

class _ShowAlertDialog extends StatefulWidget {
  final SPDialog dialog;

  const _ShowAlertDialog(
    this.dialog, {
    Key? key,
  }) : super(key: key);

  @override
  _ShowAlertDialogState createState() => _ShowAlertDialogState();
}

class _ShowAlertDialogState extends State<_ShowAlertDialog> {
  TextEditingController? editController;
  FocusNode? focusNode;
  Color btnColor = Colors.black;
  FontWeight btnTitleFontWeight = FontWeight.w600;
  bool? isEmpty = true;

  SPDialog get dialog => widget.dialog;

  @override
  void initState() {
    if (dialog.showTextField == true) {
      editController = TextEditingController(text: dialog.content!);
      editController?.addListener(() {
        isEmpty = editController?.text.trim().isEmpty;
        setState(() {});
      });
      focusNode = FocusNode();
    }
    super.initState();
  }

  @override
  void dispose() {
    focusNode?.dispose();
    editController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: Center(
        // ClipRRect 创建圆角矩形 要不然发现下边button不是圆角
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12.px),
          child: Container(
            color: Colors.white,
            width: 598.px,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                SizedBox(height: 46.px),
                (dialog.title == null || dialog.title!.isEmpty)
                    ? Container()
                    : Text(
                        dialog.title!,
                        style: TextStyle(
                            color: MyColors.color999999,
                            fontWeight: FontWeight.bold,
                            fontSize: 36.px),
                      ),
                Container(
                  padding: dialog.contentPadding ??
                      EdgeInsets.symmetric(vertical: 26.px),
                  child: Visibility(
                    visible: dialog.contentWidget == null,
                    child: Visibility(
                      visible: dialog.showTextField == true,
                      child: Container(
                        height: 84,
                        margin: const EdgeInsets.only(left: 23, right: 23),
                        padding: const EdgeInsets.only(
                            left: 16, right: 16, top: 12, bottom: 12),
                        decoration: const BoxDecoration(
                          color: Color(0xfff8f9fa),
                        ),
                        child: TextField(
                          enableInteractiveSelection: true,
                          enabled: dialog.textFieldEnabled,
                          focusNode: focusNode,
                          cursorWidth: 2,
                          cursorColor: const Color.fromRGBO(78, 97, 117, 1),
                          maxLines: 6,
                          controller: editController,
                          keyboardType: TextInputType.text,
                          inputFormatters: <TextInputFormatter>[
                            LengthLimitingTextInputFormatter(
                                dialog.textFieldMaxLength)
                          ],
                          style: TextStyle(
                              color:MyColors.color999999,
                              fontSize: 28.px),
                          decoration: InputDecoration.collapsed(
                            filled: true,
                            fillColor: const Color.fromRGBO(248, 249, 250, 1),
                            hintText: dialog.textFieldHintText,
                            hintStyle: const TextStyle(
                              color: Color.fromRGBO(186, 186, 186, 1.0),
                              fontSize: 16,
                            ),
                          ),
                          onChanged: (value) {
                            if (value.isNotEmpty) {
                              setState(() {
                                btnColor =
                                    MyColors.color333333;
                              });
                            }
                          },
                        ),
                      ),
                      replacement: Container(
                        margin: EdgeInsets.symmetric(horizontal: 30.px),
                        child: Text(
                          dialog.content ?? '',
                          style: TextStyle(
                            color: MyColors.color333333,
                            fontSize: 32.px,
                          ),
                          textAlign: dialog.contentAlign,
                        ),
                      ),
                    ),
                    replacement: dialog.contentWidget == null
                        ? Container()
                        : dialog.contentWidget!,
                  ),
                ),
                Container(
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        color:  MyColors.colorE1E1E1,
                        width: 1.px,
                      ),
                    ),
                  ),
                ),
                _itemsCreate(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _itemsCreate() {
    if (dialog.items == null) {
      return Container();
    }
    return Row(
      children: dialog.items!.map((res) {
        int index = dialog.items!.indexOf(res);

        if (dialog.showTextField == true && index == 1) {
          if (isEmpty == true) {
            btnColor = const Color.fromRGBO(186, 186, 186, 1);
          } else {
            btnColor = const Color(0xFF4E6175);
          }
        } else {
          if (dialog.items!.length > 1 && index == 1) {
            btnColor = MyColors.color333333;
            btnTitleFontWeight = FontWeight.w600;
          } else {
            btnColor = dialog.items!.length > 1
                ? MyColors.color333333
                : MyColors.color333333;
            btnTitleFontWeight =
                dialog.items!.length > 1 ? FontWeight.normal : FontWeight.w600;
          }
        }

        return Expanded(
          flex: 1,
          child: GestureDetector(
            onTap: () {
              if (dialog.showTextField == true) {
                focusNode?.unfocus();
                if (index == 0) {
                  Navigator.pop(context);
                  return;
                }
                if (editController?.text.trim().isNotEmpty == true) {
                  Navigator.pop(context);
                  dialog.textFieldOnConfirm
                      ?.call((editController?.text.trim() ?? ''));
                }
              } else {
                Navigator.pop(context);
                if (dialog.onTap != null) {
                  dialog.onTap!(index);
                }
              }
            },
            child: Container(
              height: 98.px,
              alignment: Alignment.center,
              child: Text(
                res,
                style: TextStyle(
                  color: btnColor,
                  fontSize: 32.px,
                  fontWeight: btnTitleFontWeight,
                ),
              ),
              decoration: BoxDecoration(
                border: Border(
                  right: BorderSide(
                    color: MyColors.colorE1E1E1,
                    width: 1.px,
                  ),
                ),
              ),
            ),
          ),
        );
      }).toList(),
    );
  }
}
